﻿using System;
using System.Net.Sockets;
using System.Text;
using UnityEngine;

public class Client
{
	public Action OnRequest;
	public Action<RecData> OnCallback;
	public Action<Client, RecData> DealMsg;

	public UserData UserData;
	private BaseSocket socket;
	public string RemoteEndPoint;

	private int headLength;

	public bool IsConnected
	{
		get { return socket.IsConnected; }
	}


	public Client(Socket s)
	{
		headLength = ConstantDef.headLength;
		BaseSocket baseSocket = new BaseSocket(s);
		baseSocket.OnPack += Pack;
		baseSocket.BeginReceive();
		socket = baseSocket;
		RemoteEndPoint = socket.Socket.RemoteEndPoint.ToString();
	}

	public void Send(SendData data)
	{
		socket.Send(data);
	}

	public void Pack(byte[] bytes) {
		byte[] methodBuffer = new byte[headLength];
		Buffer.BlockCopy(bytes, 0, methodBuffer, 0, headLength);

		//		MemoryStream stream = new MemoryStream(bytes);
		//		byte[] method = new byte[headLength];
		//		stream.Read(method, 0, headLength);
		short method = BitConverter.ToInt16(methodBuffer, 0);
		bool isCallback = (method & 1 << headLength * 8 - 1) > 0;
		method = (short)(method & ~(1 << headLength * 8 - 1));
		string content = Encoding.UTF8.GetString(bytes, headLength, bytes.Length - headLength);

		RecData data = new RecData(method, content, TcpState.Success);

		if (isCallback) {
			if (OnCallback != null) {
				OnCallback(data);
			}
		}

		Debug.Log("method " + method + " content is : " + content);

		if (DealMsg != null)
		{
			DealMsg(this, data);
		}
	}

//	private void DealMsg(RecData data) {
//		switch (data.ID) {
//			case MethodDef.Login:
//				UserData = JsonUtility.FromJson<UserData>(data.Content);
//
//				if (OnLogin != null)
//				{
//					OnLogin(this);
//				}
//				break;
//
//			case MethodDef.Chat:
//				break;
//		}
//	}

	public void Clear()
	{
		socket.Clear();
	}
}

public class UserData
{
	public int ID;
	public string Name;
	public string Ip;
	public int Port;

	public bool OnLine = false;
}

public class ChatData {
	public int WID;

	public int RID;

	public string Text;
}

